package com.gton.controller;

import cn.dev33.satoken.sso.SaSsoConsts;
import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaResult;
import com.gton.service.AuthLoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 前后台分离架构下集成SSO所需的代码 （SSO-Server端）
 * <p>（注：如果不需要前后端分离架构下集成SSO，可删除此包下所有代码）</p>
 *
 * @author kong
 */
@RestController
public class H5Controller {

    @Autowired
    private AuthLoginUserService authLoginUserService;

    /**
     * 获取 redirectUrl
     */
    @RequestMapping("/sso/getRedirectUrl")
    private Object getRedirectUrl(String redirect, String mode) {
        // 未登录情况下，返回 code=401
        if (StpUtil.isLogin() == false) {
            return SaResult.code(401);
        }
        // 已登录情况下，构建 redirectUrl
        if (SaSsoConsts.MODE_SIMPLE.equals(mode)) {
            // 模式一
            SaSsoUtil.checkRedirectUrl(SaFoxUtil.decoderUrl(redirect));
            return SaResult.data(redirect);
        } else {
            // 模式二或模式三
            String redirectUrl = SaSsoUtil.buildRedirectUrl(StpUtil.getLoginId(), redirect);
            return SaResult.data(redirectUrl);
        }
    }


    @RequestMapping("doLogin")
    public SaResult doLogin(String name, String pwd) {
        return authLoginUserService.queryUserNameAndPassword(name, pwd);
    }

    @RequestMapping(value = "isLogin", method = RequestMethod.GET)
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    @RequestMapping(value = "tokenInfo", method = RequestMethod.GET)
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

}
